#include "NetworkServerConnection.h"

#include <boost/thread.hpp>
#include <iostream>

#include "EventEngine.h"

using namespace ENE;

NetworkServerConnection::NetworkServerConnection(const UInt16& port)
: m_ioService(), m_networkSession(m_ioService, port)
{

}

void NetworkServerConnection::start()
{
	m_serviceThread = boost::thread(boost::bind(&boost::asio::io_service::run, &m_ioService));
}

void NetworkServerConnection::sendEvent(boost::shared_ptr<const IGameEvent> event)
{

}

void NetworkServerConnection::listen()
{
	//Continue d'ecouter des connection
	ENE::ServerSession::ListenCallback listenCallback;
	listenCallback = boost::bind(&NetworkServerConnection::handleAccept, this, boost::asio::placeholders::error, _2);
	m_networkSession.listen(listenCallback);
}

void NetworkServerConnection::handleAccept(const boost::system::error_code& error, boost::shared_ptr<SocketConnection> conn)
{
	if(!error)
	{
		Int8 clientId = 1;
		m_networkSession.addClient(clientId, conn);

		std::cout << "Server: Client connecte" << std::endl;

		std::ostringstream buffer;
		buffer.write((char*)&clientId, sizeof(Int8));
		conn->write(buffer.str());

		ENE::SocketConnection::ReadCallback readCallback;
		readCallback = boost::bind(&NetworkServerConnection::handleEventRead, this, boost::asio::placeholders::error, _2, clientId);
		conn->read(readCallback);

		listen();
	}
	else
	{
		std::cout << error.message() << std::endl;
	}
}

void NetworkServerConnection::handleEventRead(const boost::system::error_code& error, const std::vector<Int8>& data, Int8 clientId)
{
	if(!error)
	{
		std::string msg(data.begin(),data.end());
		std::cout << msg << std::endl;
	}
	else
	{
		std::cout << error.message() << std::endl;
	}
}

Int8 NetworkServerConnection::getId() const
{
	return 0;
}

void NetworkServerConnection::setEventEngine(boost::shared_ptr<EventEngine> eventEngine)
{
	m_eventEngine = eventEngine;
}